<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Api
 *
 * @author wupeng
 */
abstract class ApiAbstract {

    //put your code here

    const UPDATE_MAGE_FINANCE_API_URL = 'http://fin.uuch.com/finance/api/';
    const MAGE_FINANCE_API_TOKEN = 'f368aede8fcf242853a1fee7f20e8567';

    protected $_fields = array();
    protected $_periodStart;
    protected $_account;

    public function __construct($periodStart, $account) {
        $this->_periodStart = $periodStart;
        $this->_account = $account;
    }

    public function setFields($key, $value = null) {
        if (!is_null($value) && isset($this->_fields[$key])) {
            $this->_fields[$key] = $value;
        } elseif (is_array($key)) {
            $this->_fields = $key;
        }

        return $this;
    }

    public function getFields() {
        return $this->_fields;
    }

    abstract public function addTransaction();

    protected function _buildUrl($action) {
        $params = array(
            $action,
            'token',
            self::MAGE_FINANCE_API_TOKEN
        );

        return self::UPDATE_MAGE_FINANCE_API_URL . implode('/', $params);
    }

    protected function _updateMageFinance($url, $params) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        $result = curl_exec($ch);
        curl_close($ch);
        $message = '';
        if ($result) {
            $resultJson = json_decode($result);
            if (is_array($resultJson)) {
                foreach ($resultJson as $_result) {
                    if ('error' == (string)$_result->code) {
                        $message .= "{$_result->message}\n";
                    }
                }
            }
        } else {
            $message = curl_error($ch);
        }
        if ($message) {
            $this->_log($params, $message);
        }
        return $this;
    }

    protected function _log($params, $errorInfo = '') {
        $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'log.txt';
        $fp = fopen($file, "a");
        flock($fp, LOCK_EX);
        $now = date('Y-m-d H:i:s');
        $logInfo = "客户:{$params['customer_name']}在{$now}执行{$params['business_type']}与交易方{$params['trader']}的操作中出现异常\n{$errorInfo}\n";
        fwrite($fp, $logInfo);
        flock($fp, LOCK_UN);
        fclose($fp);
    }

}
